
package net.biaji.android.alephclient;

import java.util.ArrayList;
import java.util.Date;

import net.biaji.alephclient.Book;
import net.biaji.android.alephclient.data.DataFusionManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;

/**
 * 检查在借书籍的过期情况
 * 
 * @author biAji<biaji@biaji.net>
 */
public class ExpireChecker extends AsyncTask<Void, Void, ArrayList<Book>> {
    /**
     * 默认提前提醒时间
     */
    public static final int DEFAULT_ALARM_DATE = 3;

    private Context context;

    public ExpireChecker(Context context) {
        this.context = context;
    }

    @Override
    protected ArrayList<Book> doInBackground(Void... params) {
        return DataFusionManager.getInstance(context).getBookInPocket();
    }

    @Override
    protected void onPostExecute(ArrayList<Book> result) {
        for (Book book : result) {
            long lastDate = Book.EXPIRE_DATE
                    - (new Date().getTime() - book.getBorrowDate().getTime())
                    / (1000 * 24 * 60 * 60);
            if (lastDate < DEFAULT_ALARM_DATE) {
                NotificationManager nm = (NotificationManager) context
                        .getSystemService(Service.NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(context)
                        .setContentTitle(context.getString(R.string.expire_alert_title))
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentText(
                                String.format(context.getString(R.string.expire_alert_content),
                                        book.getName(), lastDate)).build();
                nm.notify("", 0, notification);
            }
        }
    }
}
